package com.xihuanjun.util;

import com.xihuanjun.healthcode.config.SysCache;
import com.xihuanjun.healthcode.entity.ChangeRecord;
import com.xihuanjun.healthcode.entity.dto.ChangeRecordDTO;
import com.xihuanjun.healthcode.entity.vo.ChangeRecordVO;
import lombok.Data;

import java.util.List;

/**
 * @author: 江溪浣
 * @createDate: 2022/10/27 10:46
 * @description:全量数据工具类
 */
public class GlobalDataUtils {

    public static void setData(ChangeRecordDTO record){
        String idCard = record.getIdCard();
        FindResult findResult = findData(idCard);
        if(findResult!=null){//找到了
            //删除旧数据
            deleteData(findResult);
            //新增新数据
            addData(record);
        }
    }

    private static void addData(ChangeRecordDTO record) {
        switch (record.getChangeType()){
            case 1:
                SysCache.red.add(record);
                break;
            case 2:
                SysCache.orange.add(record);
                break;
            case 3:
                SysCache.green.add(record);
                break;
        }
    }

    /**
     * 在红黄蓝三组全量数据中寻找身份证数据
     * @param idCard
     * @return
     */
    private static FindResult findData(String idCard){

        ChangeRecordDTO record = SysCache.red.stream().filter(dd -> dd.getIdCard().equals(idCard)).findFirst().orElse(null);
        if(record!=null){
            return new FindResult(record,1);
        }
        record = SysCache.orange.stream().filter(dd -> dd.getIdCard().equals(idCard)).findFirst().orElse(null);
        if(record!=null){
            return new FindResult(record,2);
        }
        record = SysCache.green.stream().filter(dd -> dd.getIdCard().equals(idCard)).findFirst().orElse(null);
        if(record!=null){
            return new FindResult(record,3);
        }
        return null;
    }

    private static void deleteData(FindResult result){
        switch (result.getYuanType()){
            case 1://从红的删除
                SysCache.red.remove(result.record);
                break;
            case 2:
                SysCache.orange.remove(result.record);
                break;
            case 3:
                SysCache.green.remove(result.record);
                break;
        }
    }

    @Data
    static class FindResult{
        private ChangeRecordDTO record;
        private int yuanType;

        public FindResult(ChangeRecordDTO record, int yuanType) {
            this.record = record;
            this.yuanType = yuanType;
        }
    }
}
